package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.MessagePropertiesUtils;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 阿里云短信服务
 */
@RestController
@RequestMapping("/msmservice/msm")
//@CrossOrigin
@Api(description = "阿里云短信服务")
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 根据手机号发送短信验证码
     * @param phone
     * @return
     */
    @ApiOperation(value = "根据手机号发送短信验证码")
    @GetMapping("sendMsm/{phone}")
    public R sendMessage(@ApiParam(value = "手机号",name = "phone",required = true)@PathVariable String phone){
        // 获取redis缓存中的验证码 如果有值直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        boolean isSend = msmService.sendMsm(phone, MessagePropertiesUtils.TEMPLATE_CODE, param);
        if (isSend) {
            // 发送短信获取验证码成功后 将验证码放入redis中 设置验证码有效时间 当再次发送前会从redis查询是否有验证码存在
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("发送短信失败");
        }
    }

}
